package com.hyzx.qbasic.admin.common.security;

import com.hyzx.qbasic.admin.model.constant.SessionKeyConst;
import com.hyzx.qbasic.admin.model.dto.AdminUserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Created by 黄江华 on 2017/9/8
 * Shiro工具类
 */

public class ShiroUtils {

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static String getCurrentUserName() {
        return (String) SecurityUtils.getSubject().getPrincipal();
    }

    public static int getCurrentUserId() {
        return getCurrentUserInfo().getUserId();
    }

    public static AdminUserInfo getCurrentUserInfo() {
        return (AdminUserInfo) getSessionAttribute(SessionKeyConst.USER_SESSION_KEY);
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static Object removeSessionAttribute(Object key) {
        return getSession().removeAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getCaptcha(String key) {
        String captcha = getSessionAttribute(key).toString();
        removeSessionAttribute(key);
        return captcha;
    }

    public static boolean hasPermission(String permission) {
        Subject subject = SecurityUtils.getSubject();
        return subject != null && subject.isPermitted(permission);
    }
}
